package com.mobile.collect.present;

import android.os.Environment;

import com.mobile.collect.R;
import com.mobile.collect.activitys.UploadActivity;
import com.mobile.collect.beans.ExportPicInfo;
import com.mobile.collect.beans.ExportResultInfo;
import com.mobile.collect.beans.UploadFileResponse;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.net.Api;
import com.mobile.collect.net.BaseObjBean;
import com.mobile.collect.utils.ZipUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.droidlover.xdroidmvp.net.XApi;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.MultipartBody;

/**
 * 类名: ExprotListPresent
 * 作者: 李学伟
 * 日期: 2020年09月30日 10:26
 * 描述:
 */
public class UploadPresent extends BasePresent<UploadActivity> {

//    ExportResultInfo resultInfo;


    public void startUpload(List<ExportResultInfo> list) {
        getV().showLoadDialog();
        Observable.fromIterable(list).flatMap(new Function<ExportResultInfo, ObservableSource<BaseObjBean<UploadFileResponse>>>() {
            @Override
            public ObservableSource<BaseObjBean<UploadFileResponse>> apply(ExportResultInfo exportResultInfo) throws Exception {
                return toUpload(exportResultInfo);
            }
        }).compose(XApi.<BaseObjBean<UploadFileResponse>>getScheduler())
                .compose(getV().<BaseObjBean<UploadFileResponse>>bindToLifecycle())
                .subscribe(new Consumer<BaseObjBean>() {
                    @Override
                    public void accept(BaseObjBean baseObjBean) {
                        getV().notifyDataSetChanged();
                    }
                }, failNeedLoginConsumer, new Action() {
                    @Override
                    public void run() throws Exception {
                        getV().uploadSuccess();
                    }
                });
    }


    public Observable toUpload(final ExportResultInfo exportResultInfo) {
        return Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter e) throws Exception {
                List<ExportPicInfo> list = exportResultInfo.getPicPathList();
                List<File> picFileList = new ArrayList<>();
                for (ExportPicInfo exportPicInfo : list) {
                    picFileList.add(new File(exportPicInfo.getExportPath()));
                }
                String exportPath = Environment.getExternalStorageDirectory() + "/" + getV().getString(R.string.app_name) + "上传";
                File dirFile = new File(exportPath);
                if (null == dirFile || !dirFile.exists()) {
                    dirFile.mkdirs();
                }
                File zipFile = new File(exportPath, exportResultInfo.getDeviceName() + ".zip");
                if (null != zipFile && zipFile.exists()) {
                    zipFile.delete();
                }
                zipFile.createNewFile();
                ZipUtils.zipFiles(picFileList, zipFile);
                e.onNext(zipFile.getPath());
                e.onComplete();
            }
        }).flatMap(new Function<String, ObservableSource<BaseObjBean<UploadFileResponse>>>() {
            @Override
            public ObservableSource<BaseObjBean<UploadFileResponse>> apply(String s) throws Exception {
                return uploadFile(exportResultInfo, exportResultInfo.getExcelPath(), s);
            }
        }).compose(getV().<BaseObjBean<UploadFileResponse>>bindToLifecycle());
    }

    public Observable uploadFile(final ExportResultInfo exportResultInfo, String xlsPath, String zipPath) {
        Observable<UploadFileResponse> xlsObservable = getFileObservable("input_excel", xlsPath);
        Observable<UploadFileResponse> zipObservable = getFileObservable("input_img", zipPath);
        return Observable.zip(xlsObservable, zipObservable, new BiFunction<UploadFileResponse, UploadFileResponse, Map<String, String>>() {
            @Override
            public Map<String, String> apply(UploadFileResponse response, UploadFileResponse response2) throws Exception {
                Map<String, String> resultMap = new HashMap<>();
                resultMap.put(response.getType(), response.getId());
                resultMap.put(response2.getType(), response2.getId());
                return resultMap;
            }
        }).flatMap(new Function<Map<String, String>, ObservableSource<BaseObjBean<UploadFileResponse>>>() {
            @Override
            public ObservableSource<BaseObjBean<UploadFileResponse>> apply(Map<String, String> requestMap) throws Exception {
                return Api.getApiService().create(getToken(), getToken(), exportResultInfo.getDeviceName(),exportResultInfo.getDeviceNum(), requestMap);
            }
        }).map(new Function<BaseObjBean<UploadFileResponse>, BaseObjBean<UploadFileResponse>>() {
            @Override
            public BaseObjBean<UploadFileResponse> apply(BaseObjBean<UploadFileResponse> baseObjBean) throws Exception {
                if (baseObjBean.getCode() == 1) {
                    exportResultInfo.setHadUploaded(true);
                    EntityManager.getInstance().saveExportResultInfo(exportResultInfo);
                }
                return baseObjBean;
            }
        });
    }


    private Observable<UploadFileResponse> getFileObservable(final String type, String filePath) {
        MultipartBody xlsBody = filesToMultipartBody(getToken(), filePath, "");
        return Api.getApiService().uploadFileWithRequestBody(xlsBody)
                .compose(XApi.<BaseObjBean<UploadFileResponse>>getApiTransformer())
                .flatMap(new Function<BaseObjBean<UploadFileResponse>, ObservableSource<UploadFileResponse>>() {
                    @Override
                    public ObservableSource<UploadFileResponse> apply(BaseObjBean<UploadFileResponse> bean) throws Exception {
                        bean.getData().setType(type);
                        return Observable.just(bean.getData());
                    }
                });
    }

}
